/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-5-10      ShiHao       first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#include <drv_lcd.h>
#include <drv_neo_pixel.h>
#include <stdint.h>
#include <drv_matrix_led.h>
#include "aht10.h"
#include "main.h"
extern TIM_HandleTypeDef htim2;
extern void MX_TIM2_Init(void); // 声明定时器初始化函数
extern TIM_HandleTypeDef htim1;
extern void MX_TIM1_Init(void); // 声明定时器初始化函数

#define DBG_TAG "main"
#define DBG_LVL         DBG_LOG
#include <rtdbg.h>

#define LCD_W 240
#define LCD_H 240

#define LED_NUMS   (19 + 30) /* LED 的数目 */
#define LED_BRIGHTNESS 255   /* LED 的亮度 */
#define LED_SATURATION 255   /* LED 的饱和度 */

#define TEMP_Y 30
#define HUMI_Y 60
#define TEMP_X 10
#define HUMI_X 10

static aht10_device_t g_aht10_dev = RT_NULL;
static float g_temperature = 0, g_humidity = 0;

// 计数变量
static int top_count = 0;
static int mid_count = 0;
static int low_count = 0;

// LCD计数显示区域坐标
#define TOP_STR_X 10
#define TOP_STR_Y 120
#define MID_STR_X 10
#define MID_STR_Y 150
#define LOW_STR_X 10
#define LOW_STR_Y 180

// 当前选中项：0=Top, 1=Mid, 2=Low
static int selected_index = 0;

// 刷新LCD计数显示，带光标
void lcd_show_counts(void)
{
    char str[32];
    // Top
    lcd_fill(TOP_STR_X, TOP_STR_Y, LCD_W-10, TOP_STR_Y+24, WHITE);
    if(selected_index == 0)
        rt_snprintf(str, sizeof(str), "Top: %d   >", top_count);
    else
        rt_snprintf(str, sizeof(str), "Top: %d", top_count);
    lcd_show_string(TOP_STR_X, TOP_STR_Y, 24, str);
    // Mid
    lcd_fill(MID_STR_X, MID_STR_Y, LCD_W-10, MID_STR_Y+24, WHITE);
    if(selected_index == 1)
        rt_snprintf(str, sizeof(str), "Mid: %d   >", mid_count);
    else
        rt_snprintf(str, sizeof(str), "Mid: %d", mid_count);
    lcd_show_string(MID_STR_X, MID_STR_Y, 24, str);
    // Low
    lcd_fill(LOW_STR_X, LOW_STR_Y, LCD_W-10, LOW_STR_Y+24, WHITE);
    if(selected_index == 2)
        rt_snprintf(str, sizeof(str), "Low: %d   >", low_count);
    else
        rt_snprintf(str, sizeof(str), "Low: %d", low_count);
    lcd_show_string(LOW_STR_X, LOW_STR_Y, 24, str);
}

// HSV转RGB（0-255）
void hsv2rgb(uint16_t h, uint8_t s, uint8_t v, uint8_t *r, uint8_t *g, uint8_t *b)
{
    float hh = h / 60.0f;
    int i = (int)hh;
    float ff = hh - i;
    float p = v * (1.0f - s / 255.0f);
    float q = v * (1.0f - (s / 255.0f) * ff);
    float t = v * (1.0f - (s / 255.0f) * (1.0f - ff));

    switch (i % 6)
    {
    case 0: *r = v; *g = t; *b = p; break;
    case 1: *r = q; *g = v; *b = p; break;
    case 2: *r = p; *g = v; *b = t; break;
    case 3: *r = p; *g = q; *b = v; break;
    case 4: *r = t; *g = p; *b = v; break;
    case 5: *r = v; *g = p; *b = q; break;
    }
}

// 蜂鸣器控制宏
#define BUZZER_ON()  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_SET)
#define BUZZER_OFF() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET)

// 绿色：短响一声
void buzzer_beep_once(void)
{
    BUZZER_ON();
    rt_thread_mdelay(500); // 响200ms
    BUZZER_OFF();
}

// 黄色：连续两声
void buzzer_beep_twice(void)
{
    for(int i=0; i<2; i++)
    {
        BUZZER_ON();
        rt_thread_mdelay(60); // 响60ms
        BUZZER_OFF();
        rt_thread_mdelay(60); // 间隔60ms
    }
}

// 红色：连续急促三声
void buzzer_beep_triple_fast(void)
{
    for(int i=0; i<3; i++)
    {
        BUZZER_ON();
        rt_thread_mdelay(30); // 响30ms
        BUZZER_OFF();
        rt_thread_mdelay(30); // 间隔30ms
    }
}

// 绿色：循环短响
void buzzer_beep_once_loop(int duration_ms)
{
    int elapsed = 0;
    while (elapsed < duration_ms)
    {
        BUZZER_ON();
        rt_thread_mdelay(80);
        BUZZER_OFF();
        rt_thread_mdelay(80);
        elapsed += 160;
    }
}

// 黄色：循环两声
void buzzer_beep_twice_loop(int duration_ms)
{
    int elapsed = 0;
    while (elapsed < duration_ms)
    {
        for (int i = 0; i < 2 && elapsed < duration_ms; i++)
        {
            BUZZER_ON();
            rt_thread_mdelay(60);
            BUZZER_OFF();
            rt_thread_mdelay(60);
            elapsed += 120;
        }
        if (elapsed < duration_ms)
        {
            rt_thread_mdelay(100); // 组间隔
            elapsed += 100;
        }
    }
}

// 红色：循环三声急促
void buzzer_beep_triple_fast_loop(int duration_ms)
{
    int elapsed = 0;
    while (elapsed < duration_ms)
    {
        for (int i = 0; i < 3 && elapsed < duration_ms; i++)
        {
            BUZZER_ON();
            rt_thread_mdelay(30);
            BUZZER_OFF();
            rt_thread_mdelay(30);
            elapsed += 60;
        }
        if (elapsed < duration_ms)
        {
            rt_thread_mdelay(100); // 组间隔
            elapsed += 100;
        }
    }
}

static void temp_humi_thread_entry(void *parameter)
{
    char temp_str[32];
    char humi_str[32];
    while (1)
    {
        if (g_aht10_dev)
        {
            g_humidity = aht10_read_humidity(g_aht10_dev);
            g_temperature = aht10_read_temperature(g_aht10_dev);
            // 清除旧数据区域
            lcd_set_color(WHITE, BLACK);
            lcd_fill(TEMP_X, TEMP_Y, LCD_W-10, TEMP_Y+24, WHITE);
            lcd_fill(HUMI_X, HUMI_Y, LCD_W-10, HUMI_Y+24, WHITE);
            rt_snprintf(temp_str, sizeof(temp_str), "Temp: %d.%d C", (int)g_temperature, (int)(g_temperature*10)%10);
            rt_snprintf(humi_str, sizeof(humi_str), "Humi: %d.%d %%", (int)g_humidity, (int)(g_humidity*10)%10);
            lcd_show_string(TEMP_X, TEMP_Y, 24, temp_str);
            lcd_show_string(HUMI_X, HUMI_Y, 24, humi_str);
        }
        rt_thread_mdelay(1000);
    }
}

static void led_thread_entry(void *parameter)
{
    neo_pixel_ops_t *neo_ops = (neo_pixel_ops_t *)parameter;
    uint32_t color_green = ((uint32_t)0x00 << 16) | ((uint32_t)0xFF << 8) | 0x00; // 绿色
    uint32_t color_yellow = ((uint32_t)0xFF << 16) | ((uint32_t)0xFF << 8) | 0x00; // 黄色
    uint32_t color_red = ((uint32_t)0xFF << 16) | ((uint32_t)0x00 << 8) | 0x00; // 红色

    uint32_t pulse_90 = 1500;  // 90度
    uint32_t pulse_180 = 2500; // 180度

    // 记录上一次输入状态
    static int last_pe15 = 0, last_pe11_14 = 0, last_pe12_13 = 0;
    int led_on = 0;

    // 启动时LED熄灭
    neo_ops->clear();
    neo_ops->show();

    while (1)
    {
        int pe11 = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_11);
        int pe12 = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_12);
        int pe13 = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_13);
        int pe14 = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_14);
        int pe15 = HAL_GPIO_ReadPin(GPIOE, GPIO_PIN_15);

        led_on = 0;

        // 绿色闪烁 + PA5舵机90度
        if (pe15 == GPIO_PIN_SET)
        {
            if (last_pe15 == 0)
            {
                top_count++;
                lcd_show_counts();
            }
            neo_ops->fill(color_green, 0, LED_NUMS);
            neo_ops->show();
            led_on = 1;
            if (last_pe15 == 0)
            {
                __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, pulse_90); // PA5
            }
            last_pe15 = 1;
            buzzer_beep_once_loop(300); // 绿色闪烁期间循环短响
            neo_ops->clear();
            neo_ops->show();
            rt_thread_mdelay(300);
        }
        else
        {
            if (last_pe15 == 1)
            {
                __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, pulse_180); // PA5
            }
            last_pe15 = 0;
        }

        // 黄色闪烁 + PA8舵机90度
        if (pe11 == GPIO_PIN_SET || pe14 == GPIO_PIN_SET)
        {
            if (last_pe11_14 == 0)
            {
                mid_count++;
                lcd_show_counts();
            }
            neo_ops->fill(color_yellow, 0, LED_NUMS);
            neo_ops->show();
            led_on = 1;
            if (last_pe11_14 == 0)
            {
                __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pulse_90); // PA8
            }
            last_pe11_14 = 1;
            buzzer_beep_twice_loop(300); // 黄色闪烁期间循环两声
            neo_ops->clear();
            neo_ops->show();
            rt_thread_mdelay(300);
        }
        else
        {
            if (last_pe11_14 == 1)
            {
                __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pulse_180); // PA8
            }
            last_pe11_14 = (pe11 == GPIO_PIN_SET || pe14 == GPIO_PIN_SET) ? 1 : 0;
        }

        // 红色闪烁 + PA2舵机90度
        if (pe12 == GPIO_PIN_SET || pe13 == GPIO_PIN_SET)
        {
            if (last_pe12_13 == 0)
            {
                low_count++;
                lcd_show_counts();
            }
            neo_ops->fill(color_red, 0, LED_NUMS);
            neo_ops->show();
            led_on = 1;
            if (last_pe12_13 == 0)
            {
                __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3, pulse_90); // PA2
            }
            last_pe12_13 = 1;
            buzzer_beep_triple_fast_loop(300); // 红色闪烁期间循环三声急促
            neo_ops->clear();
            neo_ops->show();
            rt_thread_mdelay(300);
        }
        else
        {
            if (last_pe12_13 == 1)
            {
                __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3, pulse_180); // PA2
            }
            last_pe12_13 = (pe12 == GPIO_PIN_SET || pe13 == GPIO_PIN_SET) ? 1 : 0;
        }

        // 如果没有任何高电平输入，LED熄灭，所有舵机恢复180度
        if (!led_on)
        {
            neo_ops->clear();
            neo_ops->show();
            __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, pulse_180);
            __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pulse_180);
            __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3, pulse_180);
        }

        rt_thread_mdelay(50);
    }
}

// RT-Thread按键引脚定义
#define PIN_KEY_LEFT   GET_PIN(C, 0)
#define PIN_KEY_DOWN   GET_PIN(C, 1)
#define PIN_KEY_RIGHT  GET_PIN(C, 4)
#define PIN_KEY_UP     GET_PIN(C, 5)

static void key_thread_entry(void *parameter)
{
    static int up_flag = 0, down_flag = 0, left_flag = 0, right_flag = 0;
    static int down_long_cnt = 0;
    int changed = 0;
    while (1)
    {
        changed = 0;
        // UP
        if (rt_pin_read(PIN_KEY_UP) == PIN_LOW)
        {
            rt_thread_mdelay(50);
            if (rt_pin_read(PIN_KEY_UP) == PIN_LOW)
            {
                if (!up_flag)
                {
                    if (selected_index > 0) { selected_index--; changed = 1; }
                    up_flag = 1;
                }
            }
        }
        else
        {
            up_flag = 0;
        }
        // DOWN
        if (rt_pin_read(PIN_KEY_DOWN) == PIN_LOW)
        {
            down_long_cnt += 10; // 每循环一次+10ms
            if (down_long_cnt >= 1000)
            {
                // 长按1秒，清零所有计数
                top_count = 0;
                mid_count = 0;
                low_count = 0;
                lcd_show_counts();
                // 等待松开，防止多次清零
                while (rt_pin_read(PIN_KEY_DOWN) == PIN_LOW)
                {
                    rt_thread_mdelay(10);
                }
                down_long_cnt = 0;
                continue;
            }
            rt_thread_mdelay(50);
            if (rt_pin_read(PIN_KEY_DOWN) == PIN_LOW)
            {
                if (!down_flag)
                {
                    if (selected_index < 2) { selected_index++; changed = 1; }
                    down_flag = 1;
                }
            }
        }
        else
        {
            down_flag = 0;
            down_long_cnt = 0;
        }
        // LEFT
        if (rt_pin_read(PIN_KEY_LEFT) == PIN_LOW)
        {
            rt_thread_mdelay(50);
            if (rt_pin_read(PIN_KEY_LEFT) == PIN_LOW)
            {
                if (!left_flag)
                {
                    if (selected_index == 0 && top_count > 0) { top_count--; changed = 1; }
                    if (selected_index == 1 && mid_count > 0) { mid_count--; changed = 1; }
                    if (selected_index == 2 && low_count > 0) { low_count--; changed = 1; }
                    left_flag = 1;
                }
            }
        }
        else
        {
            left_flag = 0;
        }
        // RIGHT
        if (rt_pin_read(PIN_KEY_RIGHT) == PIN_LOW)
        {
            rt_thread_mdelay(50);
            if (rt_pin_read(PIN_KEY_RIGHT) == PIN_LOW)
            {
                if (!right_flag)
                {
                    if (selected_index == 0) { top_count++; changed = 1; }
                    if (selected_index == 1) { mid_count++; changed = 1; }
                    if (selected_index == 2) { low_count++; changed = 1; }
                    right_flag = 1;
                }
            }
        }
        else
        {
            right_flag = 0;
        }
        // 有变化就刷新LCD
        if (changed)
        {
            lcd_show_counts();
        }
        rt_thread_mdelay(10); // 主循环间隔
    }
}

int main(void)
{
    // HAL库初始化
    HAL_Init();

    // 系统时钟初始化
    SystemClock_Config();

    // GPIO初始化
    MX_GPIO_Init(); // 确保GPIO初始化被执行，蜂鸣器引脚需要

    // 蜂鸣器测试：让PB0高电平，蜂鸣器响1秒
    BUZZER_ON();
    rt_thread_mdelay(1000);
    BUZZER_OFF();

    // TIM2定时器初始化（关键！）
    MX_TIM2_Init();
    MX_TIM1_Init(); // 初始化TIM1

    // 提前初始化AHT10/AHT20
    const char *i2c_bus_name = "i2c3";
    g_aht10_dev = aht10_init(i2c_bus_name);
    if (g_aht10_dev == RT_NULL)
    {
        LOG_E("AHT10/AHT20 sensor init failed!");
    }
    else
    {
        rt_thread_mdelay(50); // 适当延时，确保传感器准备好
    }

    // LCD欢迎界面
    lcd_clear(WHITE);
    lcd_set_color(WHITE, BLACK);
    const char *line1 = "Welcome to";
    int len1 = rt_strlen(line1);
    int x1 = (LCD_W - len1 * 12) / 2;
    int y1 = 60;
    lcd_show_string(x1, y1, 24, line1);
    const char *line2 = "Fangci Zhijian";
    int len2 = rt_strlen(line2);
    int x2 = (LCD_W - len2 * 12) / 2;
    int y2 = 100;
    lcd_show_string(x2, y2, 24, line2);
    const char *line3 = "Pro!";
    int len3 = rt_strlen(line3);
    int x3 = (LCD_W - len3 * 12) / 2;
    int y3 = 140;
    lcd_show_string(x3, y3, 24, line3);

    // LED初始化
    neo_pixel_ops_t *neo_ops;
    int i, t;
    uint16_t base_hue = 0;
    neo_pixel_init(&neo_ops, LED_NUMS);
    rt_thread_mdelay(10);
    // LED全灭，确保初始化后熄灭
    neo_ops->clear();
    neo_ops->show();

    // 启动TIM2的PWM输出（CH1~CH3）
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); // PA5
    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1); // PA8
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3); // PA2
    // HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4); // PA3暂不处理

    // 初始化后全部舵机转到180度（2.5ms脉宽）
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 2500); // PA5
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, 2500); // PA8
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3, 2500); // PA2
    rt_thread_mdelay(2000); // 延时2秒，确保舵机有时间转到180度

    // 彩虹流动动画3秒
    for (t = 0; t < 300; t++)
    {
        for (i = 0; i < LED_NUMS; i++)
        {
            uint16_t hue = (base_hue + (i * 360 / LED_NUMS)) % 360;
            uint8_t r, g, b;
            hsv2rgb(hue, LED_SATURATION, LED_BRIGHTNESS, &r, &g, &b);
            neo_ops->setPixelColorRGB(i, r, g, b);
        }
        neo_ops->show();
        rt_thread_mdelay(20);
        base_hue = (base_hue + 2) % 360;
    }

    // LCD进入白屏
    lcd_clear(WHITE);
    // 显示初始计数
    lcd_show_counts();

    // 启动温湿度线程
    rt_thread_t temp_humi_thread = rt_thread_create("temphumi", temp_humi_thread_entry, RT_NULL, 1024, 20, 10);
    if (temp_humi_thread != RT_NULL) rt_thread_startup(temp_humi_thread);

    // 启动LED线程
    rt_thread_t led_thread = rt_thread_create("led", led_thread_entry, neo_ops, 1024, 21, 10);
    if (led_thread != RT_NULL) rt_thread_startup(led_thread);

    // 启动按键线程
    rt_thread_t key_thread = rt_thread_create("key", key_thread_entry, RT_NULL, 512, 22, 10);
    if (key_thread != RT_NULL) rt_thread_startup(key_thread);

    // 按键引脚初始化为输入上拉
    rt_pin_mode(PIN_KEY_LEFT,  PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_KEY_DOWN,  PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_KEY_RIGHT, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(PIN_KEY_UP,    PIN_MODE_INPUT_PULLUP);

    // 主线程空转
    while (1)
    {
        rt_thread_mdelay(1000);
    }
    return 0;
}

